package com.bulls.dsp.controller;

import com.bulls.dsp.common.Response;
import com.bulls.dsp.bean.mybatis.Payment;
import com.bulls.dsp.service.IPaymentService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;

@RestController
@RequestMapping("/back_end/payment")
public class PaymentController {

    @Resource
    private IPaymentService paymentService;

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Response<?> save(@RequestBody Payment payment) {
        paymentService.insert(payment);
        return Response.builder()
                .status(HttpStatus.OK.value())
                .build();

    }

    @RequestMapping(value = "/all", method = RequestMethod.GET)
    public Response<?> findAllByAderId(@RequestParam Long aderId,
                                       @RequestParam(required = false) Date start,
                                       @RequestParam(required = false) Date end) {
        return Response.builder()
                .status(HttpStatus.OK.value())
                .data(paymentService.findByAderIdGroupByDate(aderId))
                .build();
    }

    @RequestMapping(value = "/excel", method = RequestMethod.GET)
    public void export(@RequestParam Long aderId,
                       @RequestParam(required = false) Date start,
                       @RequestParam(required = false) Date end,
                       HttpServletResponse response)
            throws IOException {

        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-disposition", "excel");
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=" + "excel");
        response.setHeader("Pragma", "No-cache");

        OutputStream outputStream = response.getOutputStream();
        Workbook workbook = paymentService.exportExcel(aderId, start, end);
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }
}
